<!--
 * @Author: wwj 3342930399@qq.com
 * @Date: 2024-03-07 17:57:16
 * @LastEditors: wwj 3342930399@qq.com
 * @LastEditTime: 2024-03-26 11:31:52
 * @FilePath: \vue\src\views\Message\sutdent.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="student">
    <div class="table" v-if="show">
      <div class="header">
        <a-form layout="inline" :form="form">
          <a-form-item label="学生姓名">
            <a-input v-model="form.name" placeholder="请输入学生姓名">
            </a-input>
          </a-form-item>
          <a-form-item label="班级">
            <a-select
              style="width: 150px"
              v-model="form.class_id"
              placeholder="请选择学生班级"
            >
              <a-select-option
                v-for="(item, index) in classList"
                :key="index"
                :value="item.value"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="年级">
            <a-select
              style="width: 150px"
              v-model="form.grade_id"
              placeholder="请选择学生年级"
            >
              <a-select-option
                v-for="(item, index) in gradeList"
                :key="index"
                :value="item.value"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
        <div class="btn">
          <a-button type="primary" @click="handleSubmit"> 确定 </a-button>
          <a-button @click="handleClear"> 清除 </a-button>
        </div>
      </div>
      <div class="operate">
        <a-button type="primary" @click="show = !show"> 新增 </a-button>
        <a-button type="primary" @click="handleDelete(checkList)">
          删除
        </a-button>
        <a-button type="primary" @click="handleExport" :loading="exportLoading">
          导出
        </a-button>
      </div>
      <div class="body">
        <vxe-table
          ref="baseTable"
          :columns="columns"
          :datalist="datalist"
          :pagination="pagination"
          :pageChange="pageChange"
          :checkboxFun="checkBox"
        >
          <template #action="{ scope }">
            <a-button type="link" size="small" @click="handleEdit(scope)">
              编辑
            </a-button>
            <a-button type="link" size="small" @click="handleDetail(scope)">
              查看
            </a-button>
            <a-button type="link" @click="handleDelete([scope])" size="small">
              删除
            </a-button>
          </template>
        </vxe-table>
      </div>
    </div>
    <div class="form" v-else>
      <a-button @click="back">返回</a-button>
      <el-form ref="form" :model="formData" label-width="150px" :rules="rules">
        <el-form-item label="学生姓名:" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入学生姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="性别:" prop="sex">
          <el-select v-model="formData.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年龄:" prop="age">
          <el-input v-model="formData.age" placeholder="请输入年龄"></el-input>
        </el-form-item>
        <el-form-item label="身份证号:" prop="id_num">
          <el-input
            v-model="formData.id_num"
            placeholder="请输入身份证号"
          ></el-input>
        </el-form-item>
        <el-form-item label="班级:" prop="class">
          <el-select v-model="formData.class_id" placeholder="请选择班级">
            <el-option
              :label="item.name"
              :value="item.value"
              v-for="(item, index) in classList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="年级:" prop="grade">
          <el-select v-model="formData.grade_id" placeholder="请选择年级">
            <el-option
              :label="item.name"
              :value="item.value"
              v-for="(item, index) in gradeList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="入学日期:" prop="enrollment_date">
          <el-col :span="11">
            <el-date-picker
              type="date"
              placeholder="选择日期"
              v-model="formData.enrollment_date"
              style="width: 100%"
            ></el-date-picker>
          </el-col>
        </el-form-item>
        <el-form-item label="家庭地址:" prop="address">
          <el-input
            v-model="formData.address"
            placeholder="请输入家庭地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="监护人姓名:" prop="guardian_name">
          <el-input
            v-model="formData.guardian_name"
            placeholder="请输入监护人姓名"
          ></el-input>
        </el-form-item>
        <el-form-item label="监护人联系方式:" prop="guardian_phone">
          <el-input
            v-model="formData.guardian_phone"
            placeholder="请输入监护人联系方式"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">保存</el-button>
          <el-button @click="notAdd">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 信息查看 -->
    <a-drawer
      title="学生信息"
      placement="right"
      :closable="false"
      :visible="visible"
      @close="onClose"
      width="700"
    >
      <a-divider>学生基本信息</a-divider>
      <p class="text-student">
        <span
          >姓名： <span>{{ formList.name }}</span></span
        >
        <span
          >性别： <span>{{ formList.sex }}</span></span
        >
      </p>
      <a-divider />
      <p class="text-student">
        <span
          >年龄： <span>{{ formList.age }}</span></span
        >
        <span
          >身份证号： <span>{{ formList.id_num }}</span></span
        >
      </p>
      <a-divider />
      <p class="text-student">
        <span
          >年级： <span>{{ formList.grade_name }}</span></span
        >
        <span
          >班级： <span>{{ formList.class_name }}</span></span
        >
      </p>
      <a-divider />
      <p class="text-student">
        <span
          >入学时间： <span>{{ formList.enrollment_date }}</span></span
        >
        <span
          >家庭地址： <span>{{ formList.address }}</span></span
        >
      </p>
      <a-divider>监护人信息</a-divider>
      <p class="text-student">
        <span
          >监护人姓名： <span>{{ formList.guardian_name }}</span></span
        >
        <span
          >监护人联系方式： <span>{{ formList.guardian_phone }}</span></span
        >
      </p>
      <a-divider dashed />
    </a-drawer>
  </div>
</template>

<script>
import vxeTable from "../../components/vxeTable.vue";
import {
  apiGetStudentList,
  apiGetClassList,
  apiGetGradeList,
  apiAddStudent,
  apiGetStudentPageList,
  apiDeleteList,
  apiExportStudent,
  apiUpdateStudent,
} from "../../api/student";
import { ShowSuccess } from "@/utils/prompt";
import { __FUNC__ } from "@/utils/func";

export default {
  components: { vxeTable },
  data() {
    return {
      visible: false,
      formData: {
        name: "",
        sex: "",
        age: "",
        id_num: "",
        class_id: "",
        grade_id: "",
        enrollment_date: "",
        address: "",
        guardian_name: "",
        guardian_phone: "",
      },
      rules: {
        name: [{ required: true, message: "请输入学生姓名", trigger: "blur" }],
        sex: [{ required: true, message: "请选择学生性别", trigger: "change" }],
        age: [{ required: true, message: "请输入学生年龄", trigger: "blur" }],
        id_num: [
          { required: true, message: "请输入学生身份证号", trigger: "change" },
        ],
        class: [{ required: true, message: "请输入学生班级", trigger: "blur" }],
        grade: [{ required: true, message: "请输入学生班级", trigger: "blur" }],
        enrollment_date: [
          { required: true, message: "请输入学生入学日期", trigger: "change" },
        ],
        address: [
          { required: true, message: "请输入学生家庭地址", trigger: "change" },
        ],
        guardian_name: [
          {
            required: true,
            message: "请输入学生监护人姓名",
            trigger: "change",
          },
        ],
        guardian_phone: [
          {
            required: true,
            message: "请输入学生监护人联系方式",
            trigger: "blur",
          },
        ],
      },
      columns: [
        { type: "checkbox", width: "5%" },
        { type: "seq", width: "5%", align: "center", title: "序号" },
        { field: "name", title: "学生姓名", width: "10%", align: "center" },
        {
          field: "sex",
          title: "性别",
          width: "10%",
          align: "center",
        },
        {
          field: "age",
          title: "年龄",
          width: "10%",
          align: "center",
        },
        {
          field: "id_num",
          title: "身份证号",
          width: "15%",
          align: "center",
        },
        {
          field: "grade_name",
          title: "年级",
          width: "10%",
          align: "center",
        },
        {
          field: "class_name",
          title: "班级",
          width: "10%",
          align: "center",
        },
        {
          field: "enrollment_date",
          title: "入学日期",
          width: "10%",
          align: "center",
        },
        {
          title: "操作",
          width: "15%",
          align: "center",
          slots: { default: "action" },
        },
      ],
      datalist: [
        {
          name: "张三",
          sex: "男",
          age: "10",
          idNum: "422822201412202514",
          class: "3年级1班",
          enrollmentDate: "2021-09-01",
        },
      ],
      pagination: {
        falg: true,
        pageSize: 10,
        total: 0,
        currentPage: 1,
      },
      checkList: [],
      form: {
        name: "",
        class_id: "",
        grade_id: "",
      },
      show: true,
      classList: [],
      gradeList: [],
      exportLoading: false,
      formList: {
        name: "",
        sex: "",
        age: "",
        id_num: "",
        class_id: "",
        class_name: "",
        grade_name: "",
        grade_id: "",
        enrollment_date: "",
        address: "",
        guardian_name: "",
        guardian_phone: "",
      },
    };
  },
  created() {
    this.getAllStudentList();
    this.getClassList();
    this.getGradeList();
  },
  methods: {
    //获取年级下拉列表
    getGradeList() {
      apiGetGradeList().then((res) => {
        console.log(res);
        this.gradeList = res.data.map((item) => {
          return {
            name: item.grade_name,
            value: item.grade_id,
          };
        });
      });
    },
    //获取班级列表下拉框
    getClassList() {
      apiGetClassList().then((res) => {
        console.log(res);
        this.classList = res.data.map((item) => {
          return {
            name: item.class_name,
            value: item.class_id,
          };
        });
      });
    },
    //初始化所有学生数据
    getAllStudentList(data) {
      if (!data) {
        data = {
          pageNum: 1,
          pageSize: 10,
        };
      }
      apiGetStudentPageList({
        pageNum: data?.pageNum,
        pageSize: data?.pageSize,
        ...this.form,
      }).then((res) => {
        this.datalist = res.data.data;
        this.checkList = [];
        this.pagination = {
          ...this.pagination,
          total: res.data.total,
          currentPage: data?.currentPage || 1,
        };
      });
    },
    //监听分页器页码变化的，在接收到新的页码后，会执行搜索请求并更新表格数据。
    pageChange(data) {
      this.pagination = data;
      this.getAllStudentList({
        ...data,
        pageNum: data.currentPage,
        pageSize: data.pageSize,
      });
    },
    //监听表格选中的行数据，将选中的行数据保存在"checkList"数组中。
    checkBox(data) {
      this.checkList = data;
    },
    //筛选
    handleSubmit() {
      console.log(this.form);
      this.getAllStudentList();
    },
    //清除
    handleClear() {
      this.form = {
        name: "",
        class_id: "",
        grade_id: "",
      };
    },
    //新增保存
    handleAdd() {
      console.log(this.formData);
      if (this.formData.id !== "") {
        apiUpdateStudent(this.formData).then((res) => {
          console.log(res);
          if (res.data.code == 200) {
            ShowSuccess("更新成功");
            this.show = !this.show;
            this.formData = {
              name: "",
              sex: "",
              age: "",
              id_num: "",
              class_id: "",
              grade_id: "",
              enrollment_date: "",
              address: "",
              guardian_name: "",
              guardian_phone: "",
            };
            this.getAllStudentList();
          }
        });
      } else {
        this.formData.enrollment_date = this.formatDate(
          this.formData.enrollment_date
        );
        apiAddStudent(this.formData).then((res) => {
          console.log(res);
          if (res.data.code == 200) {
            ShowSuccess("新增成功");
            this.show = !this.show;
            this.formData = {
              name: "",
              sex: "",
              age: "",
              id_num: "",
              class_id: "",
              grade_id: "",
              enrollment_date: "",
              address: "",
              guardian_name: "",
              guardian_phone: "",
            };
            this.getAllStudentList();
          }
        });
      }
    },
    notAdd() {
      this.show = !this.show;
      this.formData = {
        name: "",
        sex: "",
        age: "",
        id_num: "",
        class_id: "",
        grade_id: "",
        enrollment_date: "",
        address: "",
        guardian_name: "",
        guardian_phone: "",
      };
    },
    //返回
    back() {
      this.show = !this.show;
      this.formData = {
        name: "",
        sex: "",
        age: "",
        id_num: "",
        class_id: "",
        grade_id: "",
        enrollment_date: "",
        address: "",
        guardian_name: "",
        guardian_phone: "",
      };
    },
    //导出
    handleExport() {
      this.exportLoading = true;
      const that = this;
      that
        .$http({
          method: "get",
          responseType: "blob",
          url: "http://localhost:9527/student/export",
        })
        .then((res) => {
          if (!res.data) {
            return;
          }
          __FUNC__.blobToFile(res.data);
          this.exportLoading = false;
        })
        .catch(({ data }) => {
          console.log(data);
        });
    },

    //编辑
    handleEdit(data) {
      this.show = false;
      this.formData = data;
    },
    //查看
    handleDetail(data) {
      this.visible = true;
      this.formList = data;
    },
    //关闭查看
    onClose() {
      this.visible = false;
      this.formList = {
        name: "",
        sex: "",
        age: "",
        id_num: "",
        class_id: "",
        class_name: "",
        grade_name: "",
        grade_id: "",
        enrollment_date: "",
        address: "",
        guardian_name: "",
        guardian_phone: "",
      };
    },

    // 删除提示
    handleDelete(data) {
      let that = this;
      if (data.length == 0) {
        this.$message.warning("请选择删除的对象");
        return;
      }
      this.$confirm({
        title: "提示：删除后无法恢复，是否确认删除？",
        centered: true,
        onOk() {
          that.postDeleteApi(data);
        },
        onCancel() {},
        class: "test",
      });
    },
    // 删除
    postDeleteApi(data) {
      if (data.length == 0) {
        this.$message.warning("请选择删除的对象");
        return;
      }
      let ids = data.map((item) => {
        return item.student_id;
      });
      console.log(ids);
      apiDeleteList({ ids: ids }).then((res) => {
        this.$message.success("删除成功");
        this.getAllStudentList();
      });
    },
    formatDate(dateString) {
      // 创建 Date 对象并从 ISO 8601 格式的字符串中提取日期部分
      const date = new Date(dateString);
      const formattedDate = date.toISOString().split("T")[0].replace(/-/g, "_");
      return formattedDate;
    },
  },
};
</script>

<style lang="scss" scoped>
.student {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  .header {
    width: 100%;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    margin-bottom: 20px;

    .btn button {
      margin: 0 5px;
    }
    .operate {
      width: 100%;
    }
  }
  .body {
    width: 100%;
  }
}

.operate button {
  margin: 0 5px 10px 0;
}

::v-deep .el-form-item {
  width: 50%;
}

::v-deep .vxe-grid--pager-wrapper {
  background-image: linear-gradient(#e8eaec, #e8eaec);
}

.text-student {
  display: flex;
  justify-content: space-around;
  span {
    width: 45%;
  }
}
</style>
